<template>
  <div class="VR-container">
    <div class="top">
      <div class="title">
        VR锚点设置
        <el-button link type="primary" @click="goBack">返回列表</el-button>
      </div>
      <div class="btns">
        <el-button type="primary" @click="handleEditDefaultMarker">默认锚点配置</el-button>
        <el-button type="primary" >
          <span v-if="curMarkerType == 1 && isAddMarkerState" @click="cancleAdd">取消添加导航</span>
          <span v-else @click="handleAddNavigationMarker"><i class="iconfont icon-jia"></i>导航锚点</span>
        </el-button>
        <el-button type="primary" >
          <span v-if="curMarkerType == 2 && isAddMarkerState" @click="cancleAdd">取消添加信息</span>
          <span v-else @click="handleAddInfoMarker"><i class="iconfont icon-jia"></i>信息锚点</span>
        </el-button>
      </div>
    </div>
    <div class="view-container-box">
      <div data-no-touch-simulate class="view_container" ref="viewContainer" />
    </div>
    <!-- 添加导航弹框 -->
    <el-dialog  
      v-model="showNavigationMarkerDialog"
      title="编辑"
      width="650px"
      class="tabs-dialog"
    >
      <template #header>
        <el-tabs v-model="markerActiveName">
          <el-tab-pane label="内容配置" :name="0"></el-tab-pane>
          <el-tab-pane label="锚点配置" :name="1"></el-tab-pane>
        </el-tabs>
      </template>
      <el-form :model="curMarkerForm" label-width="100px">
        <template v-if="markerActiveName == 0">
          <el-form-item label="标题">
            <el-input v-model="curMarkerForm.markerTitle" placeholder="请输入标题"/>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="curMarkerForm.des" placeholder="请输入描述" type="textarea"/>
          </el-form-item>
          <el-form-item label="跳转场景">
            <el-tree-select
              v-model="curFormSceneType"
              placeholder="选择所属上级场景"
              :filter-node-method="filterNodeMethod"
              filterable
              :data="sceneData.sceneTree"
              default-expand-all
              :props="menuTreeSelectProps"
              :check-strictly="true"
              @change="handleCurFormSceneTypeChange"
          ></el-tree-select>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="curMarkerForm.next" placeholder="选择场景页面">
              <el-option
                v-for="item in curFormSceneList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
            <el-button @click="handleGoScene(curMarkerForm)" style="margin-left:10px;">跳转</el-button>
          </el-form-item>
        </template>
        <template v-if="markerActiveName == 1">
          <el-form-item label="锚点宽(px)">
            <el-input-number v-model="curMarkerForm.size.width" :min="1" placeholder="锚点宽度(px)"/>
          </el-form-item>
          <el-form-item label="锚点高(px)">
            <el-input-number v-model="curMarkerForm.size.height" :min="1" placeholder="锚点高度(px)"/>
          </el-form-item>
          <el-form-item label="字体大小(px)">
            <el-input-number v-model="curMarkerForm.t_size" :min="1" placeholder="文本字体大小(px)"/>
          </el-form-item>
          <el-form-item label="字体颜色">
            <el-color-picker v-model="curMarkerForm.t_color" />
          </el-form-item>
          <el-form-item label="锚点图标">
            <div class="VR-marker-box">
              <div class="VR-marker" v-if="curMarkerForm.navMarkerUrl">
                <img :src="curMarkerForm.navMarkerUrl" alt="" :width="curMarkerForm.size.width" :height="curMarkerForm.size.height">
              </div>
              <el-button link type="primary" v-if="curMarkerForm.navMarkerUrl" @click="handleUploadImg('navMarkerUrl')">重新上传</el-button>
              <el-button size="small" v-else @click="handleUploadImg('navMarkerUrl')">上传图片</el-button>
            </div>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="handleDeleteMarker">删除</el-button>
          <el-button @click="showNavigationMarkerDialog = false">取消</el-button>
          <el-button type="primary" @click="handleMarkerSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加信息弹框 -->
    <el-dialog
      v-model="showInfoMarkerDialog"
      title="编辑"
      width="1000px"
      class="tabs-dialog"
    >
      <template #header>
        <el-tabs v-model="markerActiveName">
          <el-tab-pane label="内容配置" :name="0"></el-tab-pane>
          <el-tab-pane label="锚点配置" :name="1"></el-tab-pane>
        </el-tabs>
      </template>
      <el-form :model="curMarkerForm" label-width="100px">
        <template v-if="markerActiveName == 0">
          <el-form-item label="标题">
            <el-input v-model="curMarkerForm.markerTitle" placeholder="请输入标题"/>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="curMarkerForm.des" type="textarea" placeholder="请输入描述"/>
          </el-form-item>
          <el-form-item label="内容" class="temp-content">
            <TinymceEditor v-model:modelValue="curMarkerForm.content" :minHeight="400" :maxHeight="600"/>
          </el-form-item>
        </template>
        <template v-if="markerActiveName == 1">
          <el-form-item label="锚点宽(px)">
            <el-input-number v-model="curMarkerForm.size.width" :min="1" placeholder="锚点宽度(px)"/>
          </el-form-item>
          <el-form-item label="锚点高(px)">
            <el-input-number v-model="curMarkerForm.size.height" :min="1" placeholder="锚点高度(px)"/>
          </el-form-item>
          <el-form-item label="字体大小(px)">
            <el-input-number v-model="curMarkerForm.t_size" :min="1" placeholder="文本字体大小(px)"/>
          </el-form-item>
          <el-form-item label="字体颜色">
            <el-color-picker v-model="curMarkerForm.t_color" />
          </el-form-item>
          <el-form-item label="锚点图标">
            <div class="VR-marker-box">
              <div class="VR-marker" v-if="curMarkerForm.infoMarkerUrl">
                <img :src="curMarkerForm.infoMarkerUrl" alt="" :width="curMarkerForm.size.width" :height="curMarkerForm.size.height">
              </div>
              <el-button link type="primary" v-if="curMarkerForm.infoMarkerUrl" @click="handleUploadImg('infoMarkerUrl')">重新上传</el-button>
              <el-button size="small" v-else @click="handleUploadImg('infoMarkerUrl')">上传图片</el-button>
            </div>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="handleDeleteMarker">删除</el-button>
          <el-button @click="showInfoMarkerDialog = false">取消</el-button>
          <el-button type="primary" @click="handleMarkerSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 默认锚点配置 -->
    <el-dialog
      v-model="showDefualtMarkerDialog"
      title="默认锚点配置"
      width="500px"
    >
      <el-form :model="defualtMarkerForm" label-width="100px">
        <el-form-item label="锚点宽(px)">
          <el-input-number v-model="defualtMarkerForm.size.width" :min="1" placeholder="锚点宽度(px)"/>
        </el-form-item>
        <el-form-item label="锚点高(px)">
          <el-input-number v-model="defualtMarkerForm.size.height" :min="1" placeholder="锚点高度(px)"/>
        </el-form-item>
        <el-form-item label="字体大小(px)">
          <el-input-number v-model="defualtMarkerForm.t_size" :min="1" placeholder="文本字体大小(px)"/>
        </el-form-item>
        <el-form-item label="字体颜色">
          <el-color-picker v-model="defualtMarkerForm.t_color" />
        </el-form-item>
        <el-form-item label="信息锚点图标">
          <div class="VR-marker-box">
            <div class="VR-marker" v-if="defualtMarkerForm.infoMarkerUrl">
              <img :src="defualtMarkerForm.infoMarkerUrl" alt="" :width="defualtMarkerForm.size.width" :height="defualtMarkerForm.size.height">
            </div>
            <el-button link type="primary" v-if="defualtMarkerForm.infoMarkerUrl" @click="handleUploadImg('infoMarkerUrl',defualtMarkerForm)">重新上传</el-button>
            <el-button size="small" v-else @click="handleUploadImg('infoMarkerUrl',defualtMarkerForm)">上传图片</el-button>
          </div>
        </el-form-item>
        <el-form-item label="导航锚点图标">
          <div class="VR-marker-box">
            <div class="VR-marker" v-if="defualtMarkerForm.navMarkerUrl">
              <img :src="defualtMarkerForm.navMarkerUrl" alt="" :width="defualtMarkerForm.size.width" :height="defualtMarkerForm.size.height">
            </div>
            <el-button link type="primary" v-if="defualtMarkerForm.navMarkerUrl" @click="handleUploadImg('navMarkerUrl',defualtMarkerForm)">重新上传</el-button>
            <el-button size="small" v-else @click="handleUploadImg('navMarkerUrl',defualtMarkerForm)">上传图片</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDefualtMarkerDialog = false">取消</el-button>
          <el-button type="primary" @click="handleDefaultMarkerSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <ImageUpload v-if="showImgUpload" v-model:showDialog="showImgUpload" :limit="1" @getImage="getImage"></ImageUpload>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { Viewer } from 'photo-sphere-viewer'
import * as PhotoSphereViewer from "photo-sphere-viewer/dist/adapters/cubemap.js";
import 'photo-sphere-viewer/dist/photo-sphere-viewer.css'
import { MarkersPlugin } from 'photo-sphere-viewer/dist/plugins/markers'
import 'photo-sphere-viewer/dist/plugins/markers.css'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from "vue-router"
import { useStore } from 'vuex'
import { getDefaultMarkerConfig, editDefaultMarkerConfig, addMarker } from "@/api/VR"

const store = useStore()
const menuTreeSelectProps = {
  children: 'children',
  label: 'title',
  value: 'id',
}
const markerActiveName = ref(0)
const router = useRouter()
let viewContainer = ref(null)
const containerData = reactive({
  viewer: null,
  markersPlugin: null
})

const sceneData = reactive({
  sceneTree: store.getters.VRTree,
  sceneList: store.getters.VRList, //所有列表 
  curSceneId: 1, // 当前渲染场景id
  allShow: false, // 场景加载完成之后导航显示
  bgsoundUrl:'', //背景音乐
})

// 当前场景图id
sceneData.curSceneId = router.currentRoute.value.query.sceneId ? router.currentRoute.value.query.sceneId : ""
// 当前场景图数据
const curSceneData = computed(()=>{
  return sceneData.sceneList.find(item => item.id == sceneData.curSceneId)
})
const initView = () => {
  containerData.viewer = new Viewer({
    container: viewContainer.value,
    adapter: typeof curSceneData.value.VRImg == 'string' ? null : PhotoSphereViewer.CubemapAdapter,
    panorama: curSceneData.value.VRImg,
    defaultZoomLvl: 50,
    // autorotateSpeed: 0.05, // 自转速度
    // autorotateDelay: 1, // 自转延时
    size: {
      height: '100%',
      width: '100%'
    },
    plugins: [
      [
        MarkersPlugin,
        {
          markers: []
        }
      ]
    ],
    navbar: null
  })
  // 获取标注插件实例
  containerData.markersPlugin = containerData.viewer.getPlugin(MarkersPlugin)
  console.log('Viewer',containerData.viewer);
}
// 加载完成之后触发
const viewerReady = () => {
  console.log('containerData.viewer',containerData.viewer);
  containerData.viewer.once('ready', () => {

    // 添加信息点
    const markerList = sceneData.sceneList.find(item => item.id == sceneData.curSceneId)?.markerList
    if(markerList) markerList.forEach(item => containerData.markersPlugin.addMarker(item))
    sceneData.allShow = true
  
    // 点击锚点触发
    containerData.markersPlugin.on('select-marker', (e, marker) => {
      if(marker.data.btnType == 1){ 
        handleNavigationMarkerClick(marker)
      }else if(marker.data.btnType == 2){ 
        handleInfoMarkerClick(marker)
      }else{ //本地vr图
        changeLocScene()
        return
      }
    })
    // 添加锚点
    containerData.viewer.on('click', (e, data) => { //全景图点击事件
      if(!isAddMarkerState.value) return
      let params = {
        btnType: curMarkerType.value,
        markerTitle: data.markerTitle,
        latitude:data.latitude,
        longitude:data.longitude,
      }
      let curAddMarker = makeMarker(params)
      if(curSceneData.value?.markerList) curSceneData.value.markerList.push(curAddMarker)
      containerData.markersPlugin.addMarker(curAddMarker)
      console.log('curSceneData',sceneData.sceneList);
      isAddMarkerState.value = false
    });
  })
}
// 制作锚点
const makeMarker = (data) => {
  let markerSrc = ''
  if(data.btnType === 1){ 
    markerSrc = curMarkerForm.value.navMarkerUrl
  }else{
    markerSrc = curMarkerForm.value.infoMarkerUrl
  }
  let curAddMarker = {
    data:{
      ...curMarkerForm.value,
      btnType: data.btnType
    },
    html: `<div style="display: flex;justify-content: center;align-items: center;flex-direction: column;" onmouseover="this.style.cursor='pointer';" onmouseout="this.style.cursor='inherit';">\n
            <span style="font-size:${curMarkerForm.value.t_size}px;background-color: rgba(0, 0, 0, .4);color: ${curMarkerForm.value.t_color};padding: 4px 8px;border-radius: 4px;">${data?.markerTitle || '-'}</span>\n
            <img src=\"${markerSrc}" width="${curMarkerForm.value.size.width}" height="${curMarkerForm.value.size.height}"/>\n 
          </div>`,
    id: curMarker.value?.id || Date.now() + "_" + Math.ceil(Math.random() * 99999999),
    latitude: data.latitude,
    longitude: data.longitude
  }
  return curAddMarker
}
// 获取场景数据 实例化场景
const getSceneListData = async () => {
  initView()
  viewerReady()
}
// 本地vr图测试
const changeLocScene = () => {
  containerData.markersPlugin.clearMarkers()
  containerData.viewer.setPanorama(
    'https://pic3.zhimg.com/v2-7c5e783ce87c27e383b31f4cac6f64ce_r.jpg',
    { longitude: 0, latitude: 0 },
    true
  ).then(() => {
    // containerData.viewer.startAutorotate()
  })
  // 缩放恢复
  containerData.viewer.zoom(0)
}
const curMarker = ref() //当前点击的锚点
const defualtMarkerForm = ref({})
const curMarkerForm = ref(JSON.parse(JSON.stringify(defualtMarkerForm.value)))
// 添加点位
const isAddMarkerState = ref(false)
const curMarkerType = ref(null) //1导航 2信息
// 添加导航点位
const handleAddNavigationMarker = () => {
  curMarkerForm.value = JSON.parse(JSON.stringify(defualtMarkerForm.value))
  curMarkerType.value = 1
  curMarker.value = null
  isAddMarkerState.value = true
}
//添加信息点位
const handleAddInfoMarker = () => {
  curMarkerForm.value = JSON.parse(JSON.stringify(defualtMarkerForm.value))
  curMarkerType.value = 2
  curMarker.value = null
  isAddMarkerState.value = true
}
// 取消添加点位
const cancleAdd = () => {
  curMarkerType.value = null
  isAddMarkerState.value = false
}
// 点击导航点位 进行配置
const showNavigationMarkerDialog = ref(false)
const handleNavigationMarkerClick = (marker) => {
  curMarker.value = containerData.markersPlugin.getCurrentMarker()
  curMarkerForm.value = marker.config.data
  showNavigationMarkerDialog.value = true
}
// 点击信息点位 进行配置
const showInfoMarkerDialog = ref(false)
const handleInfoMarkerClick = (marker) => {
  curMarker.value = containerData.markersPlugin.getCurrentMarker()
  curMarkerForm.value = marker.config.data
  showInfoMarkerDialog.value = true
}
// 添加/编辑导航锚点确认（实际点击VR图已经添加了锚点，点击锚点是进行修改，此时的锚点id是本地id）
const handleMarkerSubmit = () => {
  let markerParams = {
    btnType: curMarkerForm.value.btnType,
    markerTitle: curMarkerForm.value.markerTitle,
    latitude:curMarker.value.config.latitude,
    longitude:curMarker.value.config.longitude,
  }
  let curAddMarker = makeMarker(markerParams)
  containerData.markersPlugin.removeMarker(curMarker.value.id) //删除锚点
  containerData.markersPlugin.addMarker(curAddMarker) //重新加上锚点
  let index = curSceneData.value.markerList.findIndex(item => item.id == curMarker.value.id)
  curSceneData.value.markerList.splice(index, 1, curAddMarker) //修改后替换
  showNavigationMarkerDialog.value = false
  showInfoMarkerDialog.value = false
  markerApi()
}
// 锚点相关接口（新增、修改、删除）
const markerApi = async () => {
  let params = {
    markerList: curSceneData.value.markerList, //锚点数组
    sceneId: sceneData.curSceneId, //场景图id
  }
  let res = await addMarker(params)
  if(res.code == 20000){
    ElMessage({
      message: "操作成功",
      type: "success",
    })
  }
}
// 删除锚点
const handleDeleteMarker = () => {
  ElMessageBox.confirm(
      '<div><p style="font-size: 14px;">是否确认删除？</p></div>',
      '提示',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }
  ).then(() => {
    if(curMarker.value?.id) containerData.markersPlugin.removeMarker(curMarker.value.id)
    let index = curSceneData.value.markerList.findIndex(item => item.id == curMarker.value.id)
    curSceneData.value.markerList.splice(index, 1)
    markerApi()
    showNavigationMarkerDialog.value = false
    showInfoMarkerDialog.value = false
  })
}

// 场景切换
const handleGoScene = (val) => {
  containerData.markersPlugin.clearMarkers()
  let VRImg = sceneData.sceneList.find(item => item.id == val.next).VRImg
  sceneData.curSceneId = val.next
  containerData.viewer.setPanorama(
    VRImg,
    { longitude: 0, latitude: 0 },
    true
  ).then(() => {
    sceneData.curSceneId = val.next
    // 添加信息点
    const markerList = sceneData.sceneList.find(item => item.id == sceneData.curSceneId)?.markerList
    if(markerList) markerList.forEach(item => containerData.markersPlugin.addMarker(item))
  })
  // 缩放恢复
  containerData.viewer.zoom(0)
}
// 表单当前选择的场景
const curFormSceneType = ref('0')
const curFormSceneList = ref([])
// 选择场景类型 获取场景页面
const handleCurFormSceneTypeChange = (val) => {
  curFormSceneList.value = []
  curMarkerForm.value.next = ''
  getCurFormSceneByPid(sceneData.sceneTree, val)
}
// 递归获取列表 本地
const getCurFormSceneByPid = (arr, pid, flag = false) => {
  arr.forEach(item => {
    if(item.id == pid || flag){
      curFormSceneList.value = curFormSceneList.value.concat(item.sceneList)
      if(item.children?.length > 0){
        getCurFormSceneByPid(item.children, pid, true)
      }
    }else if(item.children?.length > 0){
      getCurFormSceneByPid(item.children, pid)
    }
  })
}
getCurFormSceneByPid(sceneData.sceneTree, '0')
// 获取默认锚点配置
const handleGetDefaultMarkerInfo = async () => {
  let defualtMarker = JSON.parse(localStorage.getItem('test-VR-default-marker'))
  if(defualtMarker){
    defualtMarkerForm.value = defualtMarker
  }else{
    defualtMarkerForm.value = {
      markerTitle: '', //锚点标题
      des: '',//描述
      content: '', //信息内容
      btnType: '', //锚点类型 1导航锚点 2信息锚点
      next: null, //将跳转的场景id
      size: { //锚点大小
        width: 60,
        height: 60
      },
      t_size: 16, //标题字体大小
      t_color: '#fff', //标题字体颜色
      infoMarkerUrl: 'http://vrproam.foxtest.net/static/gif/click.gif', //信息锚点图标
      navMarkerUrl: 'http://vrproam.foxtest.net/static/gif/rightforward.gif', //导航锚点图标
    }
  }
  let res = await getDefaultMarkerConfig()
  defualtMarkerForm.value = res.data
}
handleGetDefaultMarkerInfo()
// 默认锚点配置
const showDefualtMarkerDialog = ref(false)
const handleEditDefaultMarker = () => {
  showDefualtMarkerDialog.value = true
}
const handleDefaultMarkerSubmit = async () => {
  let res = await editDefaultMarkerConfig(defualtMarkerForm.value)
  if(res.code == 20000){
    ElMessage({
      message: "操作成功",
      type: "success",
    })
  }
  showDefualtMarkerDialog.value = false
}
// 上传图片
const showImgUpload = ref(false)   
const curForm = ref(null)
const curImgType = ref('')
const handleUploadImg = (type, form = curMarkerForm.value) => {
  curImgType.value = type
  curForm.value = form
  showImgUpload.value = true
}
const getImage = (data) => {
  curForm.value[curImgType.value] = data[0].url
} 
// 返回列表
const goBack = () => {
  router.push({path:'/VR/VRSceneList'})
}
// 场景分类对条件进行筛选
const filterNodeMethod = (value, data) => data.title.includes(value)

onMounted(() => {
  getSceneListData()
})
</script>
<style scoped lang='scss'>
.VR-container{
  width: 100%;
  box-sizing: border-box;
  background-color: #fff;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  padding: 20px 20px;
  .top{
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title{
      font-size: 18px;
      font-weight: bold;
      margin-right: 20px;
      margin-bottom: 20px;
    }
  }
  .view-container-box{
    width: 100%;
    height: calc(100vh - 230px);
    ::v-deep(.view_container) {
      overflow: hidden;
      margin: 0 10px;
      // .mark_content_container:hover {
      //   cursor: pointer;
      // }
    }
  }
}
::v-deep(.tabs-dialog){
  .el-dialog__header{
    border-bottom: none;
  }
  .el-dialog__body{
    padding-top: 0;
  }
}
.VR-ico-box{
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-direction: column;
  .VR-ico{
    height: 150px;
    margin-right: 5px;
    img{
      height: 100%;
    }
  }
  .el-button{
    margin-top: 10px;
  }
}
.VR-marker-box{
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-direction: column;
  .el-button{
    margin-top: 10px;
  }
}
</style>